﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BP.En;
using BP.OA;
using BP.Sys;
using System.Data;
using BP.DA;
using System.Text;

namespace CCOA.App.Notice
{
    /// <summary>
    /// NoticeDataService 的摘要说明
    /// </summary>
    public class NoticeDataService : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //返回值
            string s_responsetext = string.Empty;
            context.Response.ContentType = "text/plain";
            string action = context.Request["method"];
            switch (action)
            {
                case "query":
                    s_responsetext = Query();
                    break;
                case "del":
                    s_responsetext = Del();
                    break;
                case "changestate"://修改公告状态
                    s_responsetext = ChangeState();
                    break;
                case "overtop"://置顶
                    s_responsetext = OverTop();
                    break;
                case "canceltop"://取消置顶
                    s_responsetext = CancelTop();
                    break;
            }
            if (string.IsNullOrEmpty(s_responsetext))
                s_responsetext = "";
            //组装ajax字符串格式,返回调用客户端
            context.Response.Charset = "UTF-8";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.ContentType = "text/html";
            context.Response.Expires = 0;
            context.Response.Write(s_responsetext);
            context.Response.End();
        }

        /// <summary>
        /// 修改公告状态
        /// </summary>
        /// <returns></returns>
        private string ChangeState()
        {
            string oid = HttpContext.Current.Request["OID"];
            string sSql = String.Format("Update OA_Notice set NoticeSta=Case NoticeSta when 0 then 1 when 1 then 2 when 2 then 0 end where OID={0}", oid);
            int iR = BP.DA.DBAccess.RunSQL(sSql);
            return iR > 0 ? "true" : "false";
        }
        /// <summary>
        /// 取消置顶
        /// </summary>
        private string CancelTop()
        {
            string selectedid = HttpContext.Current.Request["OID"];
            string sSql = String.Format("Update OA_Notice set SetTop=''where OID={0}", selectedid);
            int iR = BP.DA.DBAccess.RunSQL(sSql);
            return iR.ToString();
        }
        /// <summary>
        /// 置顶
        /// </summary> 
        private string OverTop()
        {
            string selectedid = HttpContext.Current.Request["OID"];
            BP.OA.Notice nt = new BP.OA.Notice(Int32.Parse(selectedid));
            DateTime now = DateTime.Now;
            now = Convert.ToDateTime(String.Format("{0:yyyy-MM-dd HH:mm:ss}", now));
            nt.SetTop = now;
            string sSql = String.Format("select * from OA_Notice  order by SetTop desc", selectedid);
            BP.DA.DBAccess.RunSQL(sSql);
            nt.Update();
            int oid =Int32.Parse(HttpContext.Current.Request["OID"]);
            BP.OA.Notice notice = new BP.OA.Notice(oid);
            notice.SetTop = DateTime.Now;
            int iR = notice.Update();
            
            //返回处理结果或返回其它页面。
            if (iR > 0)
            {
                return "true";
            }
            else
            {
                return "false";
            }
        }

        /// <summary>
        /// 查询的方法
        /// </summary>
        public string Query()
        {
            //一页显示几行数据
            string pageSize = HttpContext.Current.Request["pageSize"];
            pageSize = string.IsNullOrEmpty(pageSize) ? "20" : pageSize;
            //当前页
            string page = HttpContext.Current.Request["pageNumber"];
            page = string.IsNullOrEmpty(page) ? "1" : page;
            string selCategory = HttpContext.Current.Request["noticeCatagory"];
            string con = String.Empty;
            if (selCategory != "0")
            {
                con = String.Format(" where A.FK_NoticeCategory='{0}'", selCategory);
            }
            //String.Format中第一个参数，是向其中加入一个
            string sSql = String.Format("select FK_UserNo as UserName,E.Name as UserNameText,A.FK_Dept as Dept,A.OID,A.Title,B.Name as NoticeCategory,RDT,C.Lab as Importance,A.Importance as ImportLevel,NoticeSta,d.Lab as NoticeStaTitle,SetTop"
                                 + ",(select cast(count(*) as varchar) from OA_NoticeReader where FK_NoticeNo=A.OID and ReadTime<>'')"
                                 + "      +'/'+(select cast(count(*) as varchar) from OA_NoticeReader where FK_NoticeNo=A.OID)"
                                 + "         as ReadState"
                                 + ",case when NoticeSta=0 and GetDate() between StartTime and StopTime then cast(DateDiff(d,GetDate(),StopTime) as varchar)+'天后关闭'"
                                 + "        when NoticeSta=0 and GetDate() < StartTime then cast(DateDiff(d,GetDate(),StartTime) as varchar)+'天后打开'"
                                 + "        when NoticeSta=0 and GetDate() > StopTime then '已过期'+cast(DateDiff(d,StopTime,GetDate()) as varchar)+'天'"
                                 + "        when NoticeSta=1 then '手工打开'"
                                 + "        when NoticeSta=2 then '手工关闭'  End as PublishState"
                                 + ",case when NoticeSta=0 and GetDate() between StartTime and StopTime then 4"
                                 + "        when NoticeSta=0 and GetDate() < StartTime then 3"
                                 + "        when NoticeSta=0 and GetDate() > StopTime then 5"
                                 + "        when NoticeSta=1 then 1"
                                 + "        when NoticeSta=2 then 2 End as PublishStateFlag"
                                 + " from OA_Notice A"
                                 + " inner join OA_NoticeCategory B on B.No=A.FK_NoticeCategory"
                                 + " inner join Sys_Enum C on C.IntKey=A.Importance and C.EnumKey='Importance'"
                                 + " inner join Sys_Enum D on D.IntKey=A.NoticeSta and D.EnumKey='NoticeSta'"
                                 + " INNER JOIN port_emp E on E.No = A.FK_UserNo"
                                 + con);
            if (BP.Sys.SystemConfig.AppCenterDBType == BP.DA.DBType.MySQL)
            {
                sSql = String.Format("select FK_UserNo as UserName,E.Name as UserNameText,A.FK_Dept as Dept,A.OID,A.Title,B.Name as NoticeCategory,RDT,C.Lab as Importance,A.Importance as ImportLevel,NoticeSta,d.Lab as NoticeStaTitle,SetTop,"
                                                + "CONVERT(CONCAT((select count(*) from OA_NoticeReader where FK_NoticeNo=A.OID and ReadTime<>''),'/',(select count(*) from OA_NoticeReader where FK_NoticeNo=A.OID))"
                                                + " USING gb2312)  as ReadState"
                                                + ",case when NoticeSta=0 and CURDATE() between StartTime and StopTime then CONCAT(DateDiff(CURDATE(),StopTime),'天后关闭')"
                                                + "        when NoticeSta=0 and CURDATE() < StartTime then CONCAT(DateDiff(CURDATE(),StartTime),'天后打开')"
                                                + "        when NoticeSta=0 and CURDATE() > StopTime then CONCAT('已过期',DateDiff(StopTime,CURDATE()),'天')"
                                                + "        when NoticeSta=1 then '手工打开'"
                                                + "        when NoticeSta=2 then '手工关闭'  End as PublishState"
                                                + ",case when NoticeSta=0 and CURDATE() between StartTime and StopTime then 4"
                                                + "        when NoticeSta=0 and CURDATE() < StartTime then 3"
                                                + "        when NoticeSta=0 and CURDATE() > StopTime then 5"
                                                + "        when NoticeSta=1 then 1"
                                                + "        when NoticeSta=2 then 2 End as PublishStateFlag"
                                                + " from OA_Notice A"
                                                + " inner join OA_NoticeCategory B on B.No=A.FK_NoticeCategory"
                                                + " inner join Sys_Enum C on C.IntKey=A.Importance and C.EnumKey='Importance'"
                                                + " inner join Sys_Enum D on D.IntKey=A.NoticeSta and D.EnumKey='NoticeSta'"
                                                + " INNER JOIN port_emp E on E.No = A.FK_UserNo"
                                                + con);
            }
            int count = BP.OA.Main.GetPagedRowsCount(sSql);

            DataTable dt = BP.OA.Main.GetPagedRows(sSql, -1, "order by SetTop desc,OID", int.Parse(pageSize), int.Parse(page));
            return BP.DA.DataTableConvertJson.DataTable2Json(dt, count);
        }
        //删除的方法
        private string Del()
        {
            //获取到选中行的id
            string id = HttpContext.Current.Request["OID"];
            //1.选择删除文件
            string sSql = String.Format("Select AttachFile from OA_Notice where OID={0}", id);
            BP.OA.Main.DeleteFiles_By_Sql(sSql);
            //2.再删除公告
            int iR = this.DeleteNotice(id);
            //3.最后删除阅读标志
            sSql = String.Format("Delete FROM OA_NoticeReader where FK_NoticeNo='{0}'", id);
            BP.DA.DBAccess.RunSQL(sSql);
            return "true";
        }

        private int DeleteNotice(string oid)
        {
            string sSql = String.Format("Delete FROM OA_Notice where OID={0}", oid);
            int iR = BP.DA.DBAccess.RunSQL(sSql);
            return iR;
        }
        
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}